package cn.tedu.baking.service.impl;

import cn.tedu.baking.exception.ServiceException;
import cn.tedu.baking.mapper.IUserMapper;
import cn.tedu.baking.pojo.dto.UserLoginDTO;
import cn.tedu.baking.pojo.dto.UserRegDTO;
import cn.tedu.baking.pojo.dto.UserUpdateDTO;
import cn.tedu.baking.pojo.entity.User;
import cn.tedu.baking.pojo.vo.UserVO;
import cn.tedu.baking.response.common.StatusCode;
import cn.tedu.baking.service.IUserService;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Author：毕龙
 * Date: 2024/8/14 11:15
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserMapper iUserMapper;

    @Override
    public void saveUser(UserRegDTO userRegDTO) {
        //通过用户名查询用户是否存在
        Integer i = iUserMapper.selectUserCountByUserName(userRegDTO.getUsername());
        if (i>0){
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        //将DTO的数据复制
        BeanUtils.copyProperties(userRegDTO,user);

        user.setCreateTime(new Date()).setIsAdmin(0).setImgUrl(null);
        //对密码进行md5加密算法 bcript加密算法
        String password = user.getPassword();
        //对密码进行3次md5加密 加盐算法
        for (int j = 0; j < 3; j++) {
            password = Md5Crypt.apr1Crypt(password, "abcd" + j);
        }
        user.setPassword(password);


        //注册
        i = iUserMapper.saveUser(user);
        if (i == 0)
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        //加密
    }

    @Override
    public UserVO selectUser(UserLoginDTO userLoginDTO) {

        //通过用户名查询用户的信息
        String username = userLoginDTO.getUsername();
        User user = iUserMapper.selectUserByUserName(username);

        //判断用户名
        if (username == null){
            throw new ServiceException(StatusCode.VALIDATE_ERROR);
        }

        //判断用户
        if (user == null){
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }

        //获取密码对密码进行加密
        String password = userLoginDTO.getPassword();
        for (int i = 0; i < 3; i++) {
            password = Md5Crypt.apr1Crypt(password,"abcd"+i);
        }

        //判断密码
        if (!password.equals(user.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }

        //将数据封装vo中
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user,vo);

        return vo;
    }

    @Override
    public void updateUserById(UserUpdateDTO userUpdateDTO) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        iUserMapper.updateUserById(user);
    }
}
